#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>

void ChildWrite(int fd) {
    char buffer[1024];
    int cnt = 0;
    while(1) {
        snprintf(buffer, sizeof buffer, "I am Child, pid: %d, cnt: %d\n", getpid(), cnt++);
        write(fd, buffer, strlen(buffer));
        sleep(1);
    }
}

void ParentRead(int fd) {
    char buffer[1024];
    while(1) {
        buffer[0] = '\0';
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n > 0) {
            buffer[n] = '\0';
            std::cout << "Child say: " << buffer << std::endl; 
        }
    }
}

int main() {
    std::cout << "hello vscode!" << std::endl;
    // 1. 创建管道
    int pipefd[2] = {0};// 下标 0 表示读端，1 表示写端
    int n = pipe(pipefd);
    if(n < 0) {
        std::cerr << "pipe error!" << std::endl;
        return 1;
    }
    std::cout << "读端文件描述符: " << pipefd[0] << std::endl;
    std::cout << "写端文件描述符: " << pipefd[1] << std::endl;

    // 2. 创建子进程
    pid_t pid = fork();
    if(pid == 0) {
        // 子进程 -- 关闭读端 -- 子进程需要写，即发送 “通知”
        close(pipefd[0]);
        ChildWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    // 父进程 -- 关闭写端 -- 父进程要获取到子进程的 “通知”
    close(pipefd[1]);
    ParentRead(pipefd[0]);
    waitpid(pid, nullptr, 0);
    close(pipefd[0]);
    return 0;
}